'use strict';

var receiverURL = 'ws://localhost:3000/receiver';
var crawlerIframe = function($compile, helper, rootScope, Socket) {
  return {
    strict: 'EA',
    // replace: true,
    templateUrl: '../views/iframe.html',
    scope: {
      // url: '='
      path: '=',
      isNew: '=',
      xpath: '='
    },
    link: function(scope, elem, attrs) {
      // 监听网页是否更新
      // socket.on('new webpage', function(data) {
      //   console.log('网页已更新', data);
      //   if (data.success) {
      //     // 更新成功则刷新iframe内容
      //     $compile(elem.contents())(scope);
      //   }
      // });

      // 监听iframe内容
      var ifrm = elem.find('#iframeId');

      var base;

      // iframe里的document
      var doc = ifrm[0].contentWindow.document;
      // var doc = document;
      var mirror = new TreeMirror(doc, {
        createElement: function(tagName) {
          if (tagName == 'SCRIPT') {
            var node = doc.createElement('NO-SCRIPT');
            node.style.display = 'none';
            return node;
          }

          if (tagName == 'HEAD') {
            var node = doc.createElement('HEAD');
            node.appendChild(doc.createElement('BASE'));
            node.firstChild.href = base;
            return node;
          }
        }
      });

      function clearPage() {
        while (doc.firstChild) {
          doc.removeChild(doc.firstChild);
        }
      }

      function handleMessage(msg) {
        if (msg.clear)
          clearPage();
        else if (msg.base)
          base = msg.base;
        else {
          mirror[msg.f].apply(mirror, msg.args);
          if (msg.f == 'initialize') {
            return 'initialize';
          }
        }
      }

      var receiverURL = 'ws://localhost:3000/receiver';
      var socket = Socket.connect(receiverURL);

      socket.on('connect', function() {
        console.log('receiver connected');

        socket.on('receiver', function(data) {

          var msg = JSON.parse(data);
          if (msg instanceof Array) {
            msg.forEach(function(subMessage) {
              scope.startListening = handleMessage(JSON.parse(
                subMessage));
              scope.$digest();
            });
          } else {
            scope.startListening = handleMessage(msg);
            scope.$digest();
          }
        });

        socket.on('disconnect', function() {
          socket = new WebSocket(receiverURL);
        });
      });

      var unbindWatch = scope.$watch('startListening', function(v) {
        console.log(v, 'v');
        if (v) {
          var $iframe_body = ifrm.contents().find('body');
          var $document = ifrm.contents();
          console.log(ifrm.contents().width())
          console.log(ifrm.contents().height())
            // var body2 = $(ifrm[0].contentWindow.document).find('body');
            // console.log('ifrm.contents().find(body)')
            // console.log($iframe_body);
            // console.log('ifrm[0].contentWindow.document')
            // console.log(body2)

          //产生canvas
          craetCanvas('canvasId', $document.width(), '600px',
            $iframe_body);
          // var style2 = {
          //   // 'border': '1px solid red',
          //   // 'width': $(doc).width(),
          //   // 'height': $(doc.body).height(),
          //   // 'backgroundColor':'red',
          //   'pointer-events':'none',
          //   'position':'absolute',
          //   'left':'0px',
          //   'top':'0px'
          // }
          // console.log($(doc).height(),'innerHeight');
          // // console.log($(document).outerheight,'outerheight');
          // console.log($(doc).width(),'innerwidth');
          // // console.log($(document).outerwidth,"outerwidth");
          // // $("<b>Hello World!</b>").appendTo("body");
          // // $('<canvas id= "canvasId"></canvas>').css(style2).appendTo('body');
          // ifrm.contents().find('body').append('<canvas id= "canvasId" width="'+$(doc).width()+'" height="'+$(doc.body).height()+'"></canvas>')
          // var $canvas = ifrm.contents().find('body').find('#canvasId');
          // $canvas.css(style2);
          // $('<canvas id= "canvasId"></canvas>').css(style2).appendTo('body');
          // draw()
          // unbindWatch();
          //

          // 提取规则
          $iframe_body.click(function(e) {
            e.preventDefault();
            scope.$apply(function() {
              scope.xpath = helper.getXPath(e.target)
              scope.path = helper.getElemPath(e.target);
              scope.isNew = true;
              console.log(scope.path, 'path');
              console.log(scope.xpath, 'xpath');
            });
            clearCanvas('canvasId')
            draw(scope.path, $(doc).scrollLeft(), $(doc).scrollTop())
          });


          //监听滚动条
          $($('#iframeId')[0].contentWindow).scroll(function(e) {
            var canvas = ifrm.contents().find('body').find(
                '#canvasId')
              // console.log($(doc).scrollTop())
              // console.log($(doc).scrollLeft())
            canvas.css('top', $(doc).scrollTop())
            canvas.css('left', $(doc).scrollLeft())
            clearCanvas('canvasId')
            draw(scope.path, $(doc).scrollLeft(), $(doc).scrollTop())
              // draw(scope.path)
              // $(doc).scrollTop()
              //   var style3 = {
              //   // 'border': '1px solid red',
              //   // 'width': $(doc).width(),
              //   // 'height': $(doc).scrollTop()+ $(doc.body).height(),
              //   // 'backgroundColor':'red',
              //   'pointer-events':'none',
              //   'position':'absolute',
              //   'left':'0px',
              //   'top':'0px'
              // }
              // $canvas.css(style3);
              // console.log(e)
              // console.log('scroll')
          });


          // 监听鼠标移动();
          $iframe_body.find('*').mouseenter(function(e) {
            // console.log($(this))
            // if ($(this).context.tagName == 'CANVAS') {
            //   // var index = $(this).css('z-index','-1')
            //   // draw()
            //   // console.log(index)
            // }else{
            scope.backgroundColor = [];
            scope.backgroundColor.push($(this).css(
              'backgroundColor'));
            $(this).css('backgroundColor', '#ebd85e');
            $(this).css("cursor", "Pointer");
            e.stopPropagation();
            // }
          });
          $iframe_body.find('*').mouseout(function(e) {
            if ($(this).context.tagName == 'CANVAS') {
              // var index = $(this).css('z-index','auto')
              // console.log(index)
            } else {
              e.stopPropagation();
              // console.log(angular.toJson(scope.backgroundColor,true));
              $(this).css('backgroundColor', scope.backgroundColor.pop());
            }
          });


          //监听窗口变化（1、把原来的canvasremove掉；2、根据当前的窗口新建canvas；3、把原来的path重画。）
          $(ifrm[0].contentWindow).resize(function() {
            console.log('resize')
            delCanvas('canvasId', $iframe_body)
            craetCanvas('canvasId', $document.width(), '600px',
              $iframe_body);
            // draw(scope.path)
            draw(scope.path, $(doc).scrollLeft(), $(doc).scrollTop())
          });
        }

        //监听path的变化
        scope.$watch('path', function(oldval, newval) {
          console.log('path change')
          clearCanvas('canvasId');
          if (scope.path) {
            // clearCanvas('canvasId');
            // draw(scope.path)
            draw(scope.path, $(doc).scrollLeft(), $(doc).scrollTop())
          }
        });
      });

      //根据path画出方块
      function draw(path, scrollLeft, scrollTop) {
        var canvas = ifrm.contents().find('body').find('#canvasId')[0];
        var $_path = ifrm.contents().find('body').find(path);
        // console.log($_path.length)
        // var objarry= [];
        if ($_path) {
          $_path.each(function() {
            var objStyle = {
                'top': Math.floor($(this).offset().top - scrollTop),
                'left': Math.floor($(this).offset().left - scrollLeft),
                'width': Math.floor($(this).outerWidth()),
                'height': Math.floor($(this).outerHeight() - 1)
              }
              // console.log('draw')
              // console.log(objStyle)
            if (canvas.getContext) {
              var ctx = canvas.getContext('2d');
              ctx.fillStyle = "rgba(200,0,0,0.5)";
              // ctx.fillRect(25,25,100,100);
              // ctx.clearRect(45,45,60,60);
              // ctx.strokeRect(50,50,50,50);
              ctx.clearRect(objStyle.left, objStyle.top, objStyle.width,
                objStyle.height);
              ctx.fillRect(objStyle.left, objStyle.top, objStyle.width,
                objStyle.height);
              // ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
              // ctx.fillRect (30, 30, 55, 50);
            }
          });

        }
      }

      //根据当前窗口大小新建canvas
      function craetCanvas(canvasId, width, height, addTo) {
        var style2 = {
          'pointer-events': 'none',
          'position': 'absolute',
          'z-index': '1000000000',
          'left': '0px',
          'top': '0px'
        }
        addTo.append('<canvas id= "' + canvasId + '" width="' + width +
          '" height="' + height + '"></canvas>')
        var $canvas = addTo.find('#canvasId');
        $canvas.css(style2);
        console.log('creatCanvas ok')
      }

      //清空画布
      function clearCanvas(canvasId) {
        var canvas = ifrm.contents().find('body').find('#' + canvasId)[0];
        if (canvas.getContext) {
          var ctx = canvas.getContext('2d');
          ctx.fillStyle = "rgba(200,0,0,0.5)";
          // ctx.fillRect(25,25,100,100);
          // ctx.clearRect(45,45,60,60);
          // ctx.strokeRect(50,50,50,50);
          // console.log(canvas.width)
          // console.log(canvas.height)
          ctx.clearRect(0, 0, canvas.width, canvas.height);
          // ctx.fillRect (objStyle.left, objStyle.top, objStyle.width, objStyle.height);
          // ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
          // ctx.fillRect (30, 30, 55, 50);
        }

      }

      //删除画布
      function delCanvas(canvasId, where) {
        where.find("#" + canvasId).remove();
        console.log('remove_canvas_ok')
      }

    }
  };
};

crawlerIframe.$inject = ['$compile', 'helper', '$rootScope', 'Socket'];

var app = angular.module('webpageApp');
app.directive('crawlerIframe', crawlerIframe);
